package com.example.layoutactivity.adapter

import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.layoutactivity.R
import com.example.layoutactivity.pojo.Fruit

//class FruitAdapter(activity: Activity, val resourceId:Int, data:List<Fruit>):ArrayAdapter<Fruit>(activity,resourceId,data){
//
//    inner class ViewHolder(val fruitImage:ImageView, val fruitName:TextView)
//
//    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
//        val view:View
//        val viewHolder:ViewHolder
//        if(convertView!=null){
//            view = convertView
//            viewHolder = view.tag as ViewHolder
//        }else{
//            view = LayoutInflater.from(context).inflate(resourceId,parent,false)
//            val fruitImage:ImageView = view.findViewById(R.id.fruitImage)
//            val fruitName:TextView = view.findViewById(R.id.fruitName)
//            viewHolder = ViewHolder(fruitImage, fruitName)
//            view.tag = viewHolder
//        }
//        val fruit = getItem(position)
//        if(fruit!=null){
//            viewHolder.fruitImage.setImageResource(fruit.imageId)
//            viewHolder.fruitName.text = fruit.name
//        }
//        return view
//    }
//}

class FruitAdapter(val data:List<Fruit>):RecyclerView.Adapter<FruitAdapter.ViewHolder>(){
    inner class ViewHolder(val view:View):RecyclerView.ViewHolder(view){
        val fruitImage:ImageView = view.findViewById(R.id.fruitImage)
        val fruitName:TextView = view.findViewById(R.id.fruitName)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.fruit_item,parent,false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit = data[position]
        holder.fruitImage.setImageResource(fruit.imageId)
        holder.fruitName.text = fruit.name
    }

    override fun getItemCount(): Int = data.size

}